import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/models/spring_activity_model.dart';
import '../../core/providers/spring_activity_provider.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/popup_helper.dart';
import '../../core/utils/toast_helper.dart';
import '../../core/widgets/report_popup.dart';

class ActivityContactScreen extends ConsumerStatefulWidget {
  final String activityId;

  const ActivityContactScreen({super.key, required this.activityId});

  @override
  ConsumerState<ActivityContactScreen> createState() =>
      _ActivityContactScreenState();
}

class _ActivityContactScreenState extends ConsumerState<ActivityContactScreen> {
  SpringActivityEntity? activity;
  final TextEditingController _messageController = TextEditingController();
  final List<ChatMessage> _messages = [];
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _loadActivityData();
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  void _loadActivityData() {
    final activityNotifier = ref.read(springActivityProvider.notifier);
    activity = activityNotifier.getActivityById(widget.activityId);

    if (activity != null) {
      _messages.add(
        ChatMessage(
          content: activity!.defaultMessage,
          isFromUser: false,
          timestamp: DateTime.now(),
        ),
      );
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (activity == null) {
      return Scaffold(
        body: Center(
          child: Text(
            'Activity not found',
          ).fontSize(16.sp).textColor(Colors.black),
        ),
      );
    }

    return Scaffold(
      body: Container(
        decoration: BoxDecoration(color: const Color(0xFF2AB061)),
        child: SafeArea(
          child:
              [
                _buildTopNavigationBar(),
                _buildChatArea().expanded(),
                _buildInputArea(),
              ].toColumn(),
        ),
      ),
    );
  }

  Widget _buildTopNavigationBar() {
    return Container(
      height: 60.h,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(20.r),
          bottomRight: Radius.circular(20.r),
        ),
      ),
      child: [
        Container(
          width: 30.w,
          height: 30.w,
          decoration: BoxDecoration(
            color: Colors.black,
            shape: BoxShape.circle,
          ),
          child:
              Icon(
                Icons.arrow_back_ios_new,
              ).iconSize(20.sp).iconColor(Colors.white).center(),
        ).inkWell(onTap: () => GoRouter.of(context).pop()),
        Expanded(
          child: Text(
            'Event Contact',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 24.sp,
              fontFamily: 'PoetsenOne',
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
        ),
        Container(
          width: 30.w,
          height: 30.w,
          decoration: BoxDecoration(
            color: Colors.black,
            shape: BoxShape.circle,
          ),
          child:
              Icon(
                AliIcons.iconReport,
              ).iconSize(20.sp).iconColor(Colors.white).center(),
        ).inkWell(
          onTap: () {
            PopupHelper.showReportDialog(
              context,
              onReportSubmitted: (ReportType reportType) {
                ToastHelper.success(
                  'Report submitted successfully',
                  context: context,
                );
                Future.delayed(const Duration(milliseconds: 1500), () {
                  if (mounted) {
                    GoRouter.of(context).pop();
                  }
                });
              },
              onCancelPressed: () {},
            );
          },
        ),
      ].toRow(mainAxisAlignment: MainAxisAlignment.spaceBetween),
    );
  }

  Widget _buildChatArea() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20.h),
      child: ListView.builder(
        controller: _scrollController,
        itemCount: _messages.length,
        itemBuilder: (context, index) {
          final message = _messages[index];
          return _buildMessageBubble(message);
        },
      ),
    );
  }

  Widget _buildMessageBubble(ChatMessage message) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: [
        if (!message.isFromUser) ...[
          Container(
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Colors.black, width: 1.w),
              image: DecorationImage(
                image: AssetImage('assets/resources/avatar7.png'),
                fit: BoxFit.cover,
              ),
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color: const Color(0xFFFDF5E1),
                border: Border.all(color: Colors.black, width: 2),
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(30.r),
                  topRight: Radius.circular(30.r),
                  bottomRight: Radius.circular(30.r),
                  bottomLeft: Radius.circular(30.r),
                ),
              ),
              child: Text(
                message.content,
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.black87,
                  height: 1.4,
                ),
              ),
            ),
          ),
        ] else ...[
          Expanded(
            child: Container(
              alignment: Alignment.centerRight,
              child: [
                Container(
                  constraints: BoxConstraints(maxWidth: 280.w),
                  padding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 12.h,
                  ),
                  decoration: BoxDecoration(
                    color: const Color(0xFFFDF5E1),
                    border: Border.all(color: Colors.black, width: 1.w),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(30.r),
                      topRight: Radius.circular(30.r),
                      bottomLeft: Radius.circular(30.r),
                      bottomRight: Radius.circular(30.r),
                    ),
                  ),
                  child: Text(
                    message.content,
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.black87,
                      height: 1.4,
                    ),
                  ),
                ),
                SizedBox(width: 12.w),
                Container(
                  width: 40.w,
                  height: 40.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.black, width: 2),
                    image: DecorationImage(
                      image: AssetImage(
                        ref.watch(currentUserProvider)?.avatar ??
                            'assets/resources/avatar1.png',
                      ),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ].toRow(mainAxisAlignment: MainAxisAlignment.end),
            ),
          ),
        ],
      ].toRow(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  Widget _buildInputArea() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      child: AspectRatio(
        aspectRatio: 374 / 56,
        child: Container(
          width: double.infinity,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/resources/input.png'),
              fit: BoxFit.fill,
            ),
          ),
          child: [
            SizedBox(width: 20.w),
            // 输入框
            Expanded(
              child: TextField(
                controller: _messageController,
                decoration: InputDecoration(
                  hintText: 'say something...',
                  hintStyle: TextStyle(fontSize: 14.sp, color: Colors.grey),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.zero,
                ),
                style: TextStyle(fontSize: 14.sp, color: Colors.black87),
                maxLines: null,
                textInputAction: TextInputAction.send,
                onSubmitted: (_) => _sendMessage(),
              ),
            ),
            Container(
              width: 36.w,
              height: 36.w,
              margin: EdgeInsets.only(right: 10.w),
              decoration: BoxDecoration(
                color: const Color(0xFFFFD700),
                shape: BoxShape.circle,
              ),
              child:
                  Icon(
                    AliIcons.iconSend,
                  ).iconSize(22.sp).iconColor(Colors.white).center(),
            ).inkWell(onTap: _sendMessage),
            SizedBox(width: 10.w),
          ].toRow(crossAxisAlignment: CrossAxisAlignment.center),
        ),
      ),
    );
  }

  void _sendMessage() {
    final content = _messageController.text.trim();
    if (content.isEmpty) return;

    setState(() {
      _messages.add(
        ChatMessage(
          content: content,
          isFromUser: true,
          timestamp: DateTime.now(),
        ),
      );
    });

    _messageController.clear();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }
}

class ChatMessage {
  final String content;
  final bool isFromUser;
  final DateTime timestamp;

  ChatMessage({
    required this.content,
    required this.isFromUser,
    required this.timestamp,
  });
}
